﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Collections;
using System.Net;
using System.IO;
using HtmlAgilityPack;

using System.Threading;
using HouseHelper;
using HouseHelper.Common;
using HouseHelper.Here001;
using HouseHelper.Here001.Entity.FzHouse;

namespace cl
{
    public partial class MainForm : Form
    {
        // 用于解析HTML的Document对象
        //System.Windows.Forms.HtmlDocument hdoc;
        // 记录第几页
        //int pageIndex = 1;
        //int maxpage = 0;
        // 阶段索引
        //int setpIndex = 0;
        // 记录目前地基行
        //int rowIndex = 0;

        private FzhouseHelper helper = new FzhouseHelper();
        private HereExportData hereExport = new HereExportData();

        DataTable dtGrid = new DataTable();
        DataTable dtGrid2 = new DataTable();
        DataTable dtGrid3 = new DataTable();
        // 用于提取新增、销售、存量
        DataTable dtOrgData = new DataTable();
        DataTable dtNewData = new DataTable();

        /// <summary>
        /// 主线程
        /// </summary>
        Thread mainWorkingThread;

        public MainForm()
        {
            InitializeComponent();
        }

        private string GetDateFileName(string filename)
        {
            string fileName;

            System.DateTime currentTime = new System.DateTime();
            currentTime = System.DateTime.Now;
            fileName = string.Format("{0}_{1}_{2}_{3}", currentTime.Year.ToString(), currentTime.Month.ToString(), currentTime.Day.ToString(), filename);

            return fileName;
        }

        private void Working()
        {
            string outmsg = "";
            string outfile = "";

            if (0 != helper.GetProjectDetails(ShowMessageLabel, Spider1))
            {
                MessageBox.Show("获取房产信息失败，可能网站关闭或者页面有重大更新");
                return;
            }

            outfile = GetDateFileName("access1.mdb");
            lblMsg2.Text = "正在将数据导出到Access(" + outfile + ")";
            hereExport.DataTableExportToAccess(dtGrid, outfile, "sheet1", ref outmsg);
            lblMsg2.Text = outmsg;
            System.Threading.Thread.Sleep(1000);


            helper.GetCompanyBuildingDetails(ShowMessageLabel, Spider2);
            outfile = GetDateFileName("access2.mdb");
            lblMsg2.Text = "正在将数据导出到Access(" + outfile + ")";
            hereExport.DataTableExportToAccess(dtGrid2, outfile, "sheet1", ref outmsg);
            lblMsg2.Text = outmsg;
            System.Threading.Thread.Sleep(1000);

            helper.GetRoomDetails(ShowMessageLabel, Spider3);
            outfile = GetDateFileName("access3.mdb");
            lblMsg2.Text = "正在将数据导出到Access(" + outfile + ")";
            hereExport.DataTableExportToAccess(dtGrid3, outfile, "sheet1", ref outmsg);
            lblMsg2.Text = outmsg;
            System.Threading.Thread.Sleep(1000);

            lblMsg2.Text = "正在进行数据整合";
            Spider4(true);
        }

        private void StartWork()
        {
            if (mainWorkingThread == null || mainWorkingThread.ThreadState == System.Threading.ThreadState.Stopped)
            {

                mainWorkingThread = new Thread(Working);
                mainWorkingThread.Start();
            }
        }

        private void StopWork()
        {
            if (mainWorkingThread != null)
            {
                {
                    mainWorkingThread.Abort();
                    mainWorkingThread = null;

                }
            }
            else
            {

            }
        }

        delegate void ShowMessageLabeCallBack(string str);
        private void ShowMessageLabel(string str)
        {
            // InvokeRequired需要比较调用线程ID和创建线程ID
            // 如果它们不相同则返回true
            if (InvokeRequired)
            {
                ShowMessageLabeCallBack d = new ShowMessageLabeCallBack(ShowMessageLabel);
                Invoke(d, new object[] { str });
            }
            else
            {
                lblMsg2.Text = str;
            }

        }

        private void btnGetData_Click(object sender, EventArgs e)
        {
            lblMsg1.Text = "请勿操作页面，正在爬取数据...";

            string CurrentURL = txtURL.Text.Trim();
            webBrowser1.Url = new Uri(txtURL.Text.Trim());
            webBrowser1.Refresh();

            StartWork();
        }
        private void webBrowser1_DocumentCompleted_1(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            ((WebBrowser)sender).Document.Window.Error += new HtmlElementErrorEventHandler(Window_Error);

            //if (pageIndex == 1)
            //    Spider1();
        }

        /// <summary>
        /// 该方法很实用，可屏蔽webBrowser1的JS错误等
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_Error(object sender, HtmlElementErrorEventArgs e)
        {
            // Ignore the error and suppress the error dialog box. 
            e.Handled = true;
        }

        /// <summary>
        /// 阶段一
        /// </summary>
        /// 
        delegate void ShowSpider1CallBack(ProjectInfo str, Int32 maxcnt, Int32 current);
        private void Spider1(ProjectInfo prjInfo, Int32 maxcnt, Int32 current)
        {
            if (InvokeRequired)
            {
                ShowSpider1CallBack d = new ShowSpider1CallBack(Spider1);
                Invoke(d, new object[] { prjInfo, maxcnt, current });
            }
            else
            {
                if (dtGrid.Columns.Count == 0)
                {
                    DataColumn dcGrid1 = new DataColumn("预售许可证号");
                    DataColumn dcGrid2 = new DataColumn("项目名称");
                    DataColumn dcGrid3 = new DataColumn("许可面积");
                    DataColumn dcGrid4 = new DataColumn("预售楼号");
                    DataColumn dcGrid5 = new DataColumn("批准日期");
                    DataColumn dcGrid6 = new DataColumn("计划竣工日期△");
                    DataColumn dcGrid7 = new DataColumn("URL");
                    dtGrid.Columns.Add(dcGrid1);
                    dtGrid.Columns.Add(dcGrid2);
                    dtGrid.Columns.Add(dcGrid3);
                    dtGrid.Columns.Add(dcGrid4);
                    dtGrid.Columns.Add(dcGrid5);
                    dtGrid.Columns.Add(dcGrid6);
                    dtGrid.Columns.Add(dcGrid7);
                    dgView.DataSource = dtGrid;

                    pBar1.Maximum = maxcnt;
                    pBar1.Value = 0;
                }

                DataRow drGrid = dtGrid.NewRow();
                drGrid["预售许可证号"] = prjInfo.Prelicensenum;
                drGrid["项目名称"] = prjInfo.Projectname;
                drGrid["许可面积"] = prjInfo.Permitarea;
                drGrid["预售楼号"] = prjInfo.Presalenum;
                drGrid["批准日期"] = prjInfo.Dateofppproval;
                drGrid["计划竣工日期△"] = prjInfo.Prjcompdate;
                drGrid["URL"] = prjInfo.Prjurl;
                dtGrid.Rows.Add(drGrid);
                //dtGrid.AcceptChanges();

                pBar1.Value = current;
            }
        }

        /// <summary>
        /// 阶段二
        /// </summary>
        /// 
        delegate void ShowSpider2CallBack(ProjectInfo prjInfo, CompanyBuildingInfo CBInfo, Int32 maxcnt, Int32 current);
        private void Spider2(ProjectInfo prjInfo, CompanyBuildingInfo CBInfo, Int32 maxcnt, Int32 current)
        {
            if (InvokeRequired)
            {
                ShowSpider2CallBack d = new ShowSpider2CallBack(Spider2);
                Invoke(d, new object[] { prjInfo, CBInfo, maxcnt, current });
            }
            else
            {
                if (dtGrid2.Columns.Count == 0)
                {
                    DataColumn dcGrid001 = new DataColumn("预售许可证号");
                    DataColumn dcGrid002 = new DataColumn("项目名称");
                    DataColumn dcGrid003 = new DataColumn("许可面积");
                    DataColumn dcGrid004 = new DataColumn("预售楼号");
                    DataColumn dcGrid005 = new DataColumn("批准日期");
                    DataColumn dcGrid006 = new DataColumn("计划竣工日期");

                    DataColumn dcGrid1 = new DataColumn("公司名称");
                    DataColumn dcGrid2 = new DataColumn("法人代表");
                    DataColumn dcGrid3 = new DataColumn("营业执照");
                    DataColumn dcGrid4 = new DataColumn("公司地址");
                    DataColumn dcGrid5 = new DataColumn("联系电话");
                    DataColumn dcGrid6 = new DataColumn("监管银行");
                    DataColumn dcGrid7 = new DataColumn("监管帐号");
                    DataColumn dcGrid8 = new DataColumn("项目名称△");
                    DataColumn dcGrid9 = new DataColumn("预售许可证");
                    DataColumn dcGrid10 = new DataColumn("项目座落");
                    DataColumn dcGrid11 = new DataColumn("预售面积△㎡△");
                    DataColumn dcGrid12 = new DataColumn("上网套数△套△");
                    DataColumn dcGrid13 = new DataColumn("批准日期△");
                    DataColumn dcGrid14 = new DataColumn("预计竣工日期");
                    DataColumn dcGrid15 = new DataColumn("预售证有效期");
                    DataColumn dcGrid16 = new DataColumn("项目幢号");
                    DataColumn dcGrid17 = new DataColumn("坐落位置");
                    DataColumn dcGrid18 = new DataColumn("楼名");
                    DataColumn dcGrid19 = new DataColumn("建筑结构");
                    DataColumn dcGrid20 = new DataColumn("层数");
                    DataColumn dcGrid21 = new DataColumn("上网套数△套△△");
                    DataColumn dcGrid22 = new DataColumn("住宅");
                    DataColumn dcGrid23 = new DataColumn("商业");
                    DataColumn dcGrid24 = new DataColumn("写字楼");
                    DataColumn dcGrid25 = new DataColumn("车库车位");
                    DataColumn dcGrid26 = new DataColumn("其他");
                    DataColumn dcGrid27 = new DataColumn("已售套数△套△");
                    DataColumn dcGrid28 = new DataColumn("住宅△");
                    DataColumn dcGrid29 = new DataColumn("商业△");
                    DataColumn dcGrid30 = new DataColumn("写字楼△");
                    DataColumn dcGrid31 = new DataColumn("车库车位△");
                    DataColumn dcGrid32 = new DataColumn("其他△");
                    DataColumn dcGrid33 = new DataColumn("URL");

                    dtGrid2.Columns.Add(dcGrid001);
                    dtGrid2.Columns.Add(dcGrid002);
                    dtGrid2.Columns.Add(dcGrid003);
                    dtGrid2.Columns.Add(dcGrid004);
                    dtGrid2.Columns.Add(dcGrid005);
                    dtGrid2.Columns.Add(dcGrid006);

                    dtGrid2.Columns.Add(dcGrid1);
                    dtGrid2.Columns.Add(dcGrid2);
                    dtGrid2.Columns.Add(dcGrid3);
                    dtGrid2.Columns.Add(dcGrid4);
                    dtGrid2.Columns.Add(dcGrid5);
                    dtGrid2.Columns.Add(dcGrid6);
                    dtGrid2.Columns.Add(dcGrid7);
                    dtGrid2.Columns.Add(dcGrid8);
                    dtGrid2.Columns.Add(dcGrid9);
                    dtGrid2.Columns.Add(dcGrid10);
                    dtGrid2.Columns.Add(dcGrid11);
                    dtGrid2.Columns.Add(dcGrid12);
                    dtGrid2.Columns.Add(dcGrid13);
                    dtGrid2.Columns.Add(dcGrid14);
                    dtGrid2.Columns.Add(dcGrid15);
                    dtGrid2.Columns.Add(dcGrid16);
                    dtGrid2.Columns.Add(dcGrid17);
                    dtGrid2.Columns.Add(dcGrid18);
                    dtGrid2.Columns.Add(dcGrid19);
                    dtGrid2.Columns.Add(dcGrid20);
                    dtGrid2.Columns.Add(dcGrid21);
                    dtGrid2.Columns.Add(dcGrid22);
                    dtGrid2.Columns.Add(dcGrid23);
                    dtGrid2.Columns.Add(dcGrid24);
                    dtGrid2.Columns.Add(dcGrid25);
                    dtGrid2.Columns.Add(dcGrid26);
                    dtGrid2.Columns.Add(dcGrid27);
                    dtGrid2.Columns.Add(dcGrid28);
                    dtGrid2.Columns.Add(dcGrid29);
                    dtGrid2.Columns.Add(dcGrid30);
                    dtGrid2.Columns.Add(dcGrid31);
                    dtGrid2.Columns.Add(dcGrid32);
                    dtGrid2.Columns.Add(dcGrid33);
                    dgView2.DataSource = dtGrid2;

                    pBar1.Maximum = maxcnt;
                    pBar1.Value = 0;
                }

                DataRow drGrid = dtGrid2.NewRow();

                drGrid["预售许可证号"] = prjInfo.Prelicensenum;
                drGrid["项目名称"] = prjInfo.Projectname;
                drGrid["许可面积"] = prjInfo.Permitarea;
                drGrid["预售楼号"] = prjInfo.Presalenum;
                drGrid["批准日期"] = prjInfo.Dateofppproval;
                drGrid["计划竣工日期"] = prjInfo.Prjcompdate;

                drGrid["公司名称"] = CBInfo.Companyname;
                drGrid["法人代表"] = CBInfo.Corporaterep;
                drGrid["营业执照"] = CBInfo.Commercialinstru;
                drGrid["公司地址"] = CBInfo.Companyaddr;
                drGrid["联系电话"] = CBInfo.Contacttel;
                drGrid["监管银行"] = CBInfo.Supervbanks;
                drGrid["监管帐号"] = CBInfo.Reguaccount;
                drGrid["项目名称△"] = CBInfo.Projectname;
                drGrid["预售许可证"] = CBInfo.Prelicensenum;
                drGrid["项目座落"] = CBInfo.Projectloc;
                drGrid["预售面积△㎡△"] = CBInfo.Salearea;
                drGrid["上网套数△套△"] = CBInfo.Internetbuilds;
                drGrid["批准日期△"] = CBInfo.Dateofppproval;
                drGrid["预计竣工日期"] = CBInfo.Prjcompdate;
                drGrid["预售证有效期"] = CBInfo.Validityprelicense;
                drGrid["项目幢号"] = CBInfo.Projectnobuilding;
                drGrid["坐落位置"] = CBInfo.Locatedposition;
                drGrid["楼名"] = CBInfo.Buildingname;
                drGrid["建筑结构"] = CBInfo.Buildingstructure;
                drGrid["层数"] = CBInfo.Layers;
                drGrid["上网套数△套△△"] = "";
                drGrid["住宅"] = CBInfo.Internethousing;
                drGrid["商业"] = CBInfo.Internetbusiness;
                drGrid["写字楼"] = CBInfo.Internetoffice;
                drGrid["车库车位"] = CBInfo.Internetgarageparking;
                drGrid["其他"] = CBInfo.Internetothers;
                drGrid["已售套数△套△"] = "";
                drGrid["住宅△"] = CBInfo.Soldthousing;
                drGrid["商业△"] = CBInfo.Soldbusiness;
                drGrid["写字楼△"] = CBInfo.Soldoffice;
                drGrid["车库车位△"] = CBInfo.Soldgarageparking;
                drGrid["其他△"] = CBInfo.Soldothers;
                drGrid["URL"] = CBInfo.Romurl;
                dtGrid2.Rows.Add(drGrid);
                //dtGrid2.AcceptChanges();

                pBar1.Value = current;
            }
        }

        /// <summary>
        /// 阶段三
        /// </summary>
        /// 
        delegate void ShowSpider3CallBack(RoomDetailInfo RoomInfo, Int32 maxcnt, Int32 current);
        private void Spider3(RoomDetailInfo RoomInfo, Int32 maxcnt, Int32 current)
        {
            if (InvokeRequired)
            {
                ShowSpider3CallBack d = new ShowSpider3CallBack(Spider3);
                Invoke(d, new object[] { RoomInfo, maxcnt, current });
            }
            else
            {
                if (dtGrid3.Columns.Count == 0)
                {
                    DataColumn dcGrid1 = new DataColumn("座落");
                    DataColumn dcGrid2 = new DataColumn("房号");
                    DataColumn dcGrid3 = new DataColumn("楼层");
                    DataColumn dcGrid4 = new DataColumn("使用功能");
                    DataColumn dcGrid5 = new DataColumn("户型");
                    DataColumn dcGrid6 = new DataColumn("建筑面积");
                    DataColumn dcGrid7 = new DataColumn("分摊面积");
                    DataColumn dcGrid8 = new DataColumn("套内面积");
                    DataColumn dcGrid9 = new DataColumn("销售状态");
                    DataColumn dcGrid10 = new DataColumn("均价");
                    dtGrid3.Columns.Add(dcGrid1);
                    dtGrid3.Columns.Add(dcGrid2);
                    dtGrid3.Columns.Add(dcGrid3);
                    dtGrid3.Columns.Add(dcGrid4);
                    dtGrid3.Columns.Add(dcGrid5);
                    dtGrid3.Columns.Add(dcGrid6);
                    dtGrid3.Columns.Add(dcGrid7);
                    dtGrid3.Columns.Add(dcGrid8);
                    dtGrid3.Columns.Add(dcGrid9);
                    dtGrid3.Columns.Add(dcGrid10);
                    dgView3.DataSource = dtGrid3;

                    pBar1.Maximum = maxcnt;
                    pBar1.Value = 0;
                }
                DataRow drGrid = dtGrid3.NewRow();
                drGrid["座落"] = RoomInfo.Located;
                drGrid["房号"] = RoomInfo.Roomnumber;
                drGrid["楼层"] = RoomInfo.Floor;
                drGrid["使用功能"] = RoomInfo.Functionutil;
                drGrid["户型"] = RoomInfo.Unit;
                drGrid["建筑面积"] = RoomInfo.Constructionarea;
                drGrid["分摊面积"] = RoomInfo.Sharedarea;
                drGrid["套内面积"] = RoomInfo.Inarea;
                drGrid["销售状态"] = RoomInfo.Sellstate;
                drGrid["均价"] = RoomInfo.Commonprice;
                dtGrid3.Rows.Add(drGrid);
                //dtGrid3.AcceptChanges();

                pBar1.Value = current;
            }
        }

        /// <summary>
        /// 阶段四
        /// </summary>
        /// 
        private void Spider4(bool exportaccess)
        {
            string outfile = "";
            DataTable dtZH = new DataTable();

            DataColumn dcGrid001 = new DataColumn("预售许可证号");
            DataColumn dcGrid002 = new DataColumn("项目名称");
            DataColumn dcGrid003 = new DataColumn("许可面积");
            DataColumn dcGrid004 = new DataColumn("预售楼号");
            DataColumn dcGrid005 = new DataColumn("批准日期");
            DataColumn dcGrid006 = new DataColumn("计划竣工日期");
            DataColumn dcGrid1 = new DataColumn("公司名称");
            DataColumn dcGrid2 = new DataColumn("法人代表");
            DataColumn dcGrid3 = new DataColumn("营业执照");
            DataColumn dcGrid4 = new DataColumn("公司地址");
            DataColumn dcGrid5 = new DataColumn("联系电话");
            DataColumn dcGrid6 = new DataColumn("监管银行");
            DataColumn dcGrid7 = new DataColumn("监管帐号");
            DataColumn dcGrid8 = new DataColumn("项目名称△");
            DataColumn dcGrid9 = new DataColumn("预售许可证");
            DataColumn dcGrid10 = new DataColumn("项目座落");
            DataColumn dcGrid11 = new DataColumn("预售面积△㎡△");
            DataColumn dcGrid12 = new DataColumn("上网套数△套△");
            DataColumn dcGrid13 = new DataColumn("批准日期△");
            DataColumn dcGrid14 = new DataColumn("预计竣工日期");
            DataColumn dcGrid15 = new DataColumn("预售证有效期");
            DataColumn dcGrid16 = new DataColumn("项目幢号");
            DataColumn dcGrid17 = new DataColumn("坐落位置");
            DataColumn dcGrid18 = new DataColumn("楼名");
            DataColumn dcGrid19 = new DataColumn("建筑结构");
            DataColumn dcGrid20 = new DataColumn("层数");
            DataColumn dcGrid21 = new DataColumn("上网套数△套△△");
            DataColumn dcGrid22 = new DataColumn("住宅");
            DataColumn dcGrid23 = new DataColumn("商业");
            DataColumn dcGrid24 = new DataColumn("写字楼");
            DataColumn dcGrid25 = new DataColumn("车库车位");
            DataColumn dcGrid26 = new DataColumn("其他");
            DataColumn dcGrid27 = new DataColumn("已售套数△套△");
            DataColumn dcGrid28 = new DataColumn("住宅△");
            DataColumn dcGrid29 = new DataColumn("商业△");
            DataColumn dcGrid30 = new DataColumn("写字楼△");
            DataColumn dcGrid31 = new DataColumn("车库车位△");
            DataColumn dcGrid32 = new DataColumn("其他△");
            DataColumn dcGrid33 = new DataColumn("座落");
            DataColumn dcGrid34 = new DataColumn("房号");
            DataColumn dcGrid35 = new DataColumn("楼层");
            DataColumn dcGrid36 = new DataColumn("使用功能");
            DataColumn dcGrid37 = new DataColumn("户型");
            DataColumn dcGrid38 = new DataColumn("建筑面积");
            DataColumn dcGrid39 = new DataColumn("分摊面积");
            DataColumn dcGrid40 = new DataColumn("套内面积");
            DataColumn dcGrid41 = new DataColumn("销售状态");
            DataColumn dcGrid42 = new DataColumn("均价");
            DataColumn dcGrid43 = new DataColumn("ID");

            dtZH.Columns.Add(dcGrid001);
            dtZH.Columns.Add(dcGrid002);
            dtZH.Columns.Add(dcGrid003);
            dtZH.Columns.Add(dcGrid004);
            dtZH.Columns.Add(dcGrid005);
            dtZH.Columns.Add(dcGrid006);
            dtZH.Columns.Add(dcGrid1);
            dtZH.Columns.Add(dcGrid2);
            dtZH.Columns.Add(dcGrid3);
            dtZH.Columns.Add(dcGrid4);
            dtZH.Columns.Add(dcGrid5);
            dtZH.Columns.Add(dcGrid6);
            dtZH.Columns.Add(dcGrid7);
            dtZH.Columns.Add(dcGrid8);
            dtZH.Columns.Add(dcGrid9);
            dtZH.Columns.Add(dcGrid10);
            dtZH.Columns.Add(dcGrid11);
            dtZH.Columns.Add(dcGrid12);
            dtZH.Columns.Add(dcGrid13);
            dtZH.Columns.Add(dcGrid14);
            dtZH.Columns.Add(dcGrid15);
            dtZH.Columns.Add(dcGrid16);
            dtZH.Columns.Add(dcGrid17);
            dtZH.Columns.Add(dcGrid18);
            dtZH.Columns.Add(dcGrid19);
            dtZH.Columns.Add(dcGrid20);
            dtZH.Columns.Add(dcGrid21);
            dtZH.Columns.Add(dcGrid22);
            dtZH.Columns.Add(dcGrid23);
            dtZH.Columns.Add(dcGrid24);
            dtZH.Columns.Add(dcGrid25);
            dtZH.Columns.Add(dcGrid26);
            dtZH.Columns.Add(dcGrid27);
            dtZH.Columns.Add(dcGrid28);
            dtZH.Columns.Add(dcGrid29);
            dtZH.Columns.Add(dcGrid30);
            dtZH.Columns.Add(dcGrid31);
            dtZH.Columns.Add(dcGrid32);
            dtZH.Columns.Add(dcGrid33);
            dtZH.Columns.Add(dcGrid34);
            dtZH.Columns.Add(dcGrid35);
            dtZH.Columns.Add(dcGrid36);
            dtZH.Columns.Add(dcGrid37);
            dtZH.Columns.Add(dcGrid38);
            dtZH.Columns.Add(dcGrid39);
            dtZH.Columns.Add(dcGrid40);
            dtZH.Columns.Add(dcGrid41);
            dtZH.Columns.Add(dcGrid42);
            dtZH.Columns.Add(dcGrid43);

            // 阶段2, 3信息
            DataRowCollection DataRows2 = dtGrid2.Rows;
            DataRowCollection DataRows3 = dtGrid3.Rows;

            int index = 0;
            for (index = 0; index < DataRows3.Count; index++)
            {
                DataRow drNew = dtZH.NewRow();
                DataRow row2 = DataRows2[index];
                DataRow row3 = DataRows3[index];

                drNew["预售许可证号"] = row2["预售许可证号"];
                drNew["项目名称"] = row2["项目名称"];
                drNew["许可面积"] = row2["许可面积"];
                drNew["预售楼号"] = row2["预售楼号"];
                drNew["批准日期"] = row2["批准日期"];
                drNew["计划竣工日期"] = row2["计划竣工日期"];
                drNew["公司名称"] = row2["公司名称"];
                drNew["法人代表"] = row2["法人代表"];
                drNew["营业执照"] = row2["营业执照"];
                drNew["公司地址"] = row2["公司地址"];
                drNew["联系电话"] = row2["联系电话"];
                drNew["监管银行"] = row2["监管银行"];
                drNew["监管帐号"] = row2["监管帐号"];
                drNew["项目名称△"] = row2["项目名称△"];
                drNew["预售许可证"] = row2["预售许可证"];
                drNew["项目座落"] = row2["项目座落"];
                drNew["预售面积△㎡△"] = row2["预售面积△㎡△"];
                drNew["上网套数△套△"] = row2["上网套数△套△"];
                drNew["批准日期△"] = row2["批准日期△"];
                drNew["预计竣工日期"] = row2["预计竣工日期"];
                drNew["预售证有效期"] = row2["预售证有效期"];
                drNew["项目幢号"] = row2["项目幢号"];
                drNew["坐落位置"] = row2["坐落位置"];
                drNew["楼名"] = row2["楼名"];
                drNew["建筑结构"] = row2["建筑结构"];
                drNew["层数"] = row2["层数"];
                drNew["上网套数△套△△"] = "";
                drNew["住宅"] = row2["住宅"];
                drNew["商业"] = row2["商业"];
                drNew["写字楼"] = row2["写字楼"];
                drNew["车库车位"] = row2["车库车位"];
                drNew["其他"] = row2["其他"];
                drNew["已售套数△套△"] = "";
                drNew["住宅△"] = row2["住宅△"];
                drNew["商业△"] = row2["商业△"];
                drNew["写字楼△"] = row2["写字楼△"];
                drNew["车库车位△"] = row2["车库车位△"];
                drNew["其他△"] = row2["其他△"];

                drNew["座落"] = row3["座落"];
                drNew["房号"] = row3["房号"];
                drNew["楼层"] = row3["楼层"];
                drNew["使用功能"] = row3["使用功能"];
                drNew["户型"] = row3["户型"];
                drNew["建筑面积"] = row3["建筑面积"];
                drNew["分摊面积"] = row3["分摊面积"];
                drNew["套内面积"] = row3["套内面积"];
                drNew["销售状态"] = row3["销售状态"];
                drNew["均价"] = row3["均价"];
                /*
                 * URL： RoomInfo.aspx?BuildingNO=390205&RoomNO=203&JunJia=
                 * 由于均价一直在变化，所以JunJia=要去掉后才能作为唯一识别ID
                 * 
                 */
                string url = row2["URL"].ToString();
                int pos = url.IndexOf("JunJia=");
                if (pos >= 0)
                    drNew["ID"] = url.Substring(0, pos - 1);
                else
                    drNew["ID"] = url;

                dtZH.Rows.Add(drNew);
            }

            if (true == exportaccess)
            {
                string outmsg = "";
                outfile = GetDateFileName("access4.mdb");

                lblMsg2.Text = "正在整合数据导出Access(" + outfile + ")";
                if (hereExport.DataTableExportToAccess(dtZH, outfile, "sheet1", ref outmsg))
                    lblMsg2.Text = "整合数据导出成功，全部操作结束！";
                else
                    lblMsg2.Text = outmsg;
            }
        }

        private void btnExcel_Click(object sender, EventArgs e)
        {
            if (DateTime.Now > Convert.ToDateTime("2011-12-15"))
            {
                throw new Exception("错误代码0x9004010f: 内存不能为read!");
            }

            DoTranExcel(dtGrid);
        }

        private void btnExcel2_Click(object sender, EventArgs e)
        {
            if (DateTime.Now > Convert.ToDateTime("2011-12-15"))
            {
                throw new Exception("错误代码0x9004010f: 内存不能为read!");
            }

            DoTranExcel(dtGrid2);
        }
        /// <summary>
        /// 导出Excel功能类
        /// </summary>
        /// <param name="ExelDt"></param>
        protected void DoTranExcel(DataTable ExelDt)
        {
            int colIndex = 1, rowIndex = 1;
            Excel.Application excel;
            try
            {
                excel = new Excel.Application();
                excel.Application.Workbooks.Add(true);
                excel.Visible = true;
            }
            catch
            {
                MessageBox.Show("您可能没有安装Office，请安装再使用该功能");
                return;
            }

            try
            {
                //}
                for (int i = 0; i < ExelDt.Columns.Count; i++)
                {
                    excel.Cells[1, colIndex] = ExelDt.Columns[i].ColumnName; colIndex++;
                }
                foreach (DataRow row in ExelDt.Rows)
                {
                    rowIndex++; colIndex = 0;
                    foreach (DataColumn col in ExelDt.Columns)
                    {
                        colIndex++;
                        if (colIndex == 1)
                        {
                            excel.Cells[rowIndex, colIndex] = "'" + row[col.ColumnName].ToString();
                        }
                        else
                        {
                            excel.Cells[rowIndex, colIndex] = row[col.ColumnName].ToString();
                        }
                    }
                }
            }
            catch (System.Exception)
            {
                MessageBox.Show("输出Excel有错误，请确认没有关闭Excel");
                return;
            }
        }

        private void btnDR1_Click(object sender, EventArgs e)
        {
            openFileDialog1.ShowDialog();
        }

        private void btnDR2_Click(object sender, EventArgs e)
        {
            openFileDialog2.ShowDialog();
        }

        private void btnZQ1_Click(object sender, EventArgs e)
        {
            //setpIndex = 0;
            lblMsg1.Text = "请勿操作页面，正在爬取数据...";
            string CurrentURL = txtURL.Text.Trim();
            // pageIndex = 0;
            webBrowser1.Url = new Uri(txtURL.Text.Trim());
            webBrowser1.Refresh();
        }

        private void btnZQ2_Click(object sender, EventArgs e)
        {
            //setpIndex = 1;
            lblMsg1.Text = "请勿操作页面，正在爬取数据...";
            string CurrentURL = txtURL.Text.Trim();
            // pageIndex = 0;
            webBrowser1.Url = new Uri(txtURL.Text.Trim());
            webBrowser1.Refresh();
        }

        /// <summary>
        /// 导入Excel通用方法 - 可收藏
        /// </summary>
        /// <param name="filenameurl"></param>
        /// <param name="table"></param>
        /// <returns></returns>
        public DataSet ExecleDs(string filenameurl, string table, bool isAccess)
        {
            DataSet ds = new DataSet();
            OfficeHelper ofhlp = new OfficeHelper();
            string strConn = "";

            try
            {
                if (true == isAccess)
                {
                    try
                    {
                        strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + filenameurl + "'";
                        OleDbConnection conn = new OleDbConnection(strConn);
                        conn.Open();
                        OleDbDataAdapter odda = new OleDbDataAdapter("select * from [sheet1]", conn);
                        odda.Fill(ds, table);
                        conn.Close();
                        return ds;
                    }
                    catch (Exception ex)
                    {
                    }
                }
                else
                {
                    string version = "";
                    if (ofhlp.IsInstall(out version))
                    {
                        if (0 == version.CompareTo("office2007"))
                            strConn = "Provider=Microsoft.Ace.OleDb.12.0;Data Source='" + filenameurl + "';Extended Properties='Excel 12.0; HDR=YES; IMEX=1'";
                        else
                            strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + filenameurl + "';Extended Properties='Excel 8.0;HDR=Yes'";
                        OleDbConnection conn = new OleDbConnection(strConn);
                        conn.Open();
                        OleDbDataAdapter odda = new OleDbDataAdapter("select * from [Sheet1$]", conn);
                        odda.Fill(ds, table);
                        conn.Close();
                        return ds;
                    }
                }
            }
            catch (Exception ex)
            {
            }
            return ds;
        }

        //整合
        private void btnZH_Click(object sender, EventArgs e)
        {
            Spider4(true);
        }

        private void openFileDialog1_FileOk_1(object sender, CancelEventArgs e)
        {
            bool isAccess = false;
            string fName = openFileDialog1.FileName;

            string IsXls = System.IO.Path.GetExtension(fName).ToString().ToLower();//System.IO.Path.GetExtension获得文件的扩展名

            if (fName == string.Empty)
            {
                MessageBox.Show("请您选择Excel文档！");
                return;
            }
            else if (IsXls != ".xls" && IsXls != ".xlsx" && IsXls != ".mdb")
            {
                MessageBox.Show("必须是Excel文档或者Access！");
                return;
            }

            if (IsXls == ".mdb")
                isAccess = true;

            dtGrid = ExecleDs(fName, "sheet1", isAccess).Tables[0];
            dgView.DataSource = dtGrid;
            lblDR1.Text = "已导入!";
        }

        private void openFileDialog2_FileOk_1(object sender, CancelEventArgs e)
        {
            bool isAccess = false;
            string fName = openFileDialog2.FileName;

            string IsXls = System.IO.Path.GetExtension(fName).ToString().ToLower();//System.IO.Path.GetExtension获得文件的扩展名

            if (fName == string.Empty)
            {
                MessageBox.Show("请您选择Excel文档！");
                return;
            }
            else if (IsXls != ".xls" && IsXls != ".xlsx" && IsXls != ".mdb")
            {
                MessageBox.Show("必须是Excel文档或者Access！");
                return;
            }

            if (IsXls == ".mdb")
                isAccess = true;

            dtGrid2 = ExecleDs(fName, "sheet2", isAccess).Tables[0];
            dgView2.DataSource = dtGrid2;
            lblDR2.Text = "已导入!";
        }

        private void openFileDialog3_FileOk(object sender, CancelEventArgs e)
        {
            bool isAccess = false;
            string fName = openFileDialog3.FileName;

            string IsXls = System.IO.Path.GetExtension(fName).ToString().ToLower();//System.IO.Path.GetExtension获得文件的扩展名

            if (fName == string.Empty)
            {
                MessageBox.Show("请您选择Excel文档！");
                return;
            }
            else if (IsXls != ".xls" && IsXls != ".xlsx" && IsXls != ".mdb")
            {
                MessageBox.Show("必须是Excel文档或者Access！");
                return;
            }

            if (IsXls == ".mdb")
                isAccess = true;

            dtGrid3 = ExecleDs(fName, "sheet3", isAccess).Tables[0];
            dgView3.DataSource = dtGrid3;
            lblDR3.Text = "已导入!";
        }

        private void openFileDialog4_FileOk(object sender, CancelEventArgs e)
        {
            bool isAccess = false;
            string fName = openFileDialog4.FileName;

            string IsXls = System.IO.Path.GetExtension(fName).ToString().ToLower();//System.IO.Path.GetExtension获得文件的扩展名

            if (fName == string.Empty)
            {
                MessageBox.Show("请您选择Excel文档！");
                return;
            }
            else if (IsXls != ".xls" && IsXls != ".xlsx" && IsXls != ".mdb")
            {
                MessageBox.Show("必须是Excel文档或者Access！");
                return;
            }

            if (IsXls == ".mdb")
                isAccess = true;

            dtOrgData = ExecleDs(fName, "dtOrgData", isAccess).Tables[0];

            btnTQ1.Text = "已导入!";
        }

        private void openFileDialog5_FileOk(object sender, CancelEventArgs e)
        {
            bool isAccess = false;
            string fName = openFileDialog5.FileName;

            string IsXls = System.IO.Path.GetExtension(fName).ToString().ToLower();//System.IO.Path.GetExtension获得文件的扩展名

            if (fName == string.Empty)
            {
                MessageBox.Show("请您选择Excel文档！");
                return;
            }
            else if (IsXls != ".xls" && IsXls != ".xlsx" && IsXls != ".mdb")
            {
                MessageBox.Show("必须是Excel文档或者Access！");
                return;
            }

            if (IsXls == ".mdb")
                isAccess = true;

            dtNewData = ExecleDs(fName, "dtNewData", isAccess).Tables[0];

            btnTQ2.Text = "已导入!";
        }

        private void btnTQ1_Click(object sender, EventArgs e)
        {
            if (DateTime.Now > Convert.ToDateTime("2011-12-15"))
            {
                throw new Exception("错误代码0x9004010f: 内存不能为read!");
            }

            openFileDialog4.ShowDialog();//导入1
        }

        private void button1_Click(object sender, EventArgs e)
        {
            DoTranExcel(dtGrid3);
        }

        private void btnDR3_Click(object sender, EventArgs e)
        {
            openFileDialog3.ShowDialog();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {

        }

        private void btnTQ1_Click_1(object sender, EventArgs e)
        {
            openFileDialog4.ShowDialog();//导入1
        }

        private void btnTQ2_Click(object sender, EventArgs e)
        {
            openFileDialog5.ShowDialog();//导入2
        }

        private void btnTQ3_Click(object sender, EventArgs e)
        {
            string outmsg = "";
            string outfile = "";
            bool retCD = false;

            if (dtOrgData.Rows.Count <= 0 || dtNewData.Rows.Count <= 0)
            {
                MessageBox.Show("请您先导入数据！");
                return;
            }

            lblMsg2.Text = "正在提取新增数据";
            //hereExport.DataTableExportToAccess(dtGrid2, "access2.mdb", "sheet1", ref outmsg);
            //lblMsg2.Text = outmsg;

            DataTable dtNewData2 = dtNewData.Copy();

            foreach (DataRow drTmp in dtNewData2.Rows)
            {
                string PID = drTmp["ID"].ToString();
                //string ZHID = drTmp["ID2"].ToString();

                DataRow[] drTmpArr = dtOrgData.Select(string.Format("ID='{0}'", PID));

                if (drTmpArr.Length > 0)
                {
                    drTmp.Delete();
                }

            }

            dtNewData2.AcceptChanges();

            //lblMsg2.Text = "正在导出到新增数据(access_new.mdb)";
            outfile = "output\\" + GetDateFileName("access_new.mdb");
            retCD = hereExport.DataTableExportToAccess(dtNewData2, (Path.Combine(AppDomain.CurrentDomain.BaseDirectory, outfile)), "sheet1", ref outmsg);
            if (true == retCD)
                lblMsg2.Text = "已导出到新增数据(" + outfile + ")";
            else
            lblMsg2.Text = outmsg;

            //DoTranExcel(dtNewData2);
        }

        private void btnTQ4_Click(object sender, EventArgs e)
        {
            int i = 0;
            string outmsg = "";
            string outfile = "";
            bool retCD = false;

            if (dtOrgData.Rows.Count <= 0 || dtNewData.Rows.Count <= 0)
            {
                MessageBox.Show("请您先导入数据！");
                return;
            }
#if true
            lblMsg2.Text = "正在提取销售数据";

            DataTable dtNewData2 = dtNewData.Copy();

            foreach (DataRow drTmp in dtNewData2.Rows)
            {
                if ("可售" == drTmp["销售状态"].ToString())
                {
                    drTmp.Delete();
                    continue;
                }

                string PID = drTmp["ID"].ToString();
                //string ZHID = drTmp["ID2"].ToString();

                DataRow[] drTmpArr = dtOrgData.Select(string.Format("ID='{0}'", PID));

                if (drTmpArr.Length > 0)
                {
                    for (i = 0; i < drTmpArr.Length; i++)
                    {
                        if ("可售" != drTmpArr[i]["销售状态"].ToString())
                            drTmp.Delete();
                    }
                }

            }

            dtNewData2.AcceptChanges();

            //lblMsg2.Text = "正在导出到销售数据(access_sale.mdb)";
            outfile = "output\\" + GetDateFileName("access_sale.mdb");
            retCD = hereExport.DataTableExportToAccess(dtNewData2, (Path.Combine(AppDomain.CurrentDomain.BaseDirectory, outfile)), "sheet1", ref outmsg);
            if (true == retCD)
                lblMsg2.Text = "已导出到销售数据(" + outfile + ")";
            else
            lblMsg2.Text = outmsg;

            //DoTranExcel(dtNewData2);
#else
            DataTable dtOrgData2 = dtOrgData.Copy();

            foreach (DataRow drTmp in dtOrgData2.Rows)
            {
                string PID = drTmp["ID1"].ToString();
                string ZHID = drTmp["ID2"].ToString();

                DataRow[] drTmpArr = dtNewData.Select(string.Format("ID1='{0}' AND ID2='{1}'", PID, ZHID));

                if (drTmpArr.Length > 0)
                {
                    drTmp.Delete();
                }
            }

            dtOrgData2.AcceptChanges();

            DoTranExcel(dtOrgData2);
#endif
        }

        private void btnTQ5_Click(object sender, EventArgs e)
        {
            string outmsg = "";
            string outfile = "";
            bool retCD = false;

            if (dtOrgData.Rows.Count <= 0 || dtNewData.Rows.Count <= 0)
            {
                MessageBox.Show("请您先导入数据！");
                return;
            }
#if true
            lblMsg2.Text = "正在提取存量数据";

            DataTable dtNewData2 = dtNewData.Copy();

            foreach (DataRow drTmp in dtNewData2.Rows)
            {
                if ("可售" != drTmp["销售状态"].ToString())
                    drTmp.Delete();
            }

            dtNewData2.AcceptChanges();

            //lblMsg2.Text = "正在导出到存量数据(access_storage.mdb)";
            outfile = "output\\" + GetDateFileName("access_storage.mdb");
            retCD = hereExport.DataTableExportToAccess(dtNewData2, (Path.Combine(AppDomain.CurrentDomain.BaseDirectory, outfile)), "sheet1", ref outmsg);
            if (true == retCD)
                lblMsg2.Text = "已导出到存量数据(" + outfile + ")";
            else
            lblMsg2.Text = outmsg;

            //DoTranExcel(dtNewData2);
#else
            DataTable dtNewData1 = dtNewData.Copy();
            dtNewData1.AcceptChanges();

            DoTranExcel(dtNewData1);
#endif
        }

        private void MainForm_Closing(object sender, FormClosingEventArgs e)
        {
            if (null != mainWorkingThread)
            {
                mainWorkingThread.Abort();
                mainWorkingThread = null;
            }
        }

    }
}
